/*
 * ServiceFactory.java
 *
 * Created on 02 March 2006, 16:08
 *
 * To change this template, choose Tools | Options and locate the template under
 * the Source Creation and Management node. Right-click the template and choose
 * Open. You can then make changes to the template in the Source Editor.
 */

package web.services;

import ajax.services.GenericAjaxService;
import java.util.HashMap;
import web.exceptions.ServiceNotFoundException;

/**
 *
 * @author Phil
 */
public class ServiceFactory {
    
    private static final String SERVICE_PACKAGE = "web.services.";
    private static final String AJAX_SERVICE_PACKAGE = "ajax.services.";
    private HashMap <String,Service> serviceMap = new HashMap <String,Service>();
    private static ServiceFactory instance;
    
    /** Creates a new instance of ServiceFactory */
    private ServiceFactory() {
    }
    
    public synchronized static ServiceFactory getInstance() {
        if (null == instance) {
            instance = new ServiceFactory();
        }
        return instance;
    }
    
    public GenericAjaxService getAjaxService(String serviceName) throws ServiceNotFoundException {
        return ((GenericAjaxService)getAService(serviceName, AJAX_SERVICE_PACKAGE));
    }
    
     public Service getService(String serviceName) throws ServiceNotFoundException {
        return getAService(serviceName, SERVICE_PACKAGE);
    }
    
    private synchronized Service getAService(String serviceName, String servicePackage) throws ServiceNotFoundException {
        Service currentService = serviceMap.get(serviceName);
        try {
            if (null == currentService) {
                currentService = (Service) Class.forName(servicePackage + serviceName).newInstance();
                serviceMap.put(serviceName, currentService);
            }
        } catch (Exception e) {
            throw new ServiceNotFoundException(serviceName + " could not be found/created!");
        }
        return currentService;
    }
}
